package com.kcht.sylyg08.service;


import com.kcht.adp.common.ThreadManager;
import com.kcht.adp.common.log.Logger;
import com.kcht.sylyg08.dao.ICommandPerDao;
import com.kcht.sylyg08.service.model.Upload;
import com.kcth.sylyg08.entity.CommandPer;
import com.kcth.sylyg08.entity.ReportStatus;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


/**
 * 数据是异步上传的，是否上传成功需要一定的时间，
 * 当响应报文返回成功时CommandPer表需要更新,
 * 后续可能需要自动重传
 * @author domjc
 */
@Singleton
//@Startup
@Deprecated
public class CommandPerManager {
    @Inject
    private Logger logger;
    @Inject
    private IAsyncReportToMes asyncReportToMes;
    @Inject
    private ThreadManager threadManager;

    @Inject
    private ICommandPerDao commandPerDao;

//    @PostConstruct
    public void autoRetransmission() {
        threadManager.post(this::updateCommandPerTable);
    }


    /**
     *
     * 更新CommandPer表信息
     * */
    private void updateCommandPerTable() {
        while (true) {
            Upload upload;
            synchronized (asyncReportToMes.getAsyncFutures()) {
                upload = asyncReportToMes.getAsyncFutures().pollFirst();
                if (upload == null) {
                    try {
                        asyncReportToMes.getAsyncFutures().wait();
                    } catch (InterruptedException e) {
                        logger.info("更新CommandPer表信息的线程意外中断");
                    }
                    continue;
                }
            }
            judgeResp(upload);
        }
    }

    /**
     * 获取响应并判断响应
     * */
    private void judgeResp(Upload upload){
        Future<Response> respFuture = upload.getRespFuture();
        Client client=upload.getClient();
        Response response = null;
        try {
            response = respFuture.get(10000L, TimeUnit.MILLISECONDS);
            logger.info("MES返回的报文状态  ---> "+ response.getStatus());
            if (response.getStatus() == 200) {
                logger.info("ReportToMes  --->  上报成功, 工位: "+upload.getUploadedData().getStaCode()+", EPC: "+upload.getUploadedData().getEpcCode());
                updateCommandPerTable(upload.getUploadedData(), 0);
            } else {
                logger.info("ReportToMes  --->  上报失败");
                updateCommandPerTable(upload.getUploadedData(), 1);
            }
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            logger.info("ReportToMes  --->  上报失败，连接错误");
            updateCommandPerTable(upload.getUploadedData(), 1);
        } finally {
            if (response != null) {
                response.close();
                client.close();
            }
        }
    }

    /**
     * 更新
     * */
    private void updateCommandPerTable(CommandPer commandPer, int reportResult) {
        if (0 == reportResult) {
            commandPer.setReportStatus(ReportStatus.成功);
            commandPerDao.merge(commandPer);
        } else if (1 == reportResult) {
            commandPer.setReportStatus(ReportStatus.失败);
            commandPerDao.merge(commandPer);
        }
    }


}
